package branch.feature.signin_and_signup

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.example.myapplication.R
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import java.io.IOException

class SignActivity : Activity() {
    private lateinit var client: OkHttpClient

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sign_ss)
        client = OkHttpClient()
        initListener()
    }

    private fun initListener() {
        val register_btn = findViewById<Button>(R.id.register_btn)
        val login_btn = findViewById<Button>(R.id.login_btn)
        val username_te = findViewById<EditText>(R.id.username_te)
        val password_te = findViewById<EditText>(R.id.password_te)
        register_btn.setOnClickListener {
            val username = username_te.text.toString()
            val password = password_te.text.toString()
            if (username.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "用户名和密码不能为空!", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val json = """
                {
                    "username":"$username",
                    "password":"$password"
                }
            """.trimIndent()

            // 发送注册请求
            sendPostRequest(Constant.register_url, json)
        }

        login_btn.setOnClickListener {
            val username = username_te.text.toString()
            val password = password_te.text.toString()
            if (username.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "用户名和密码不能为空！", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            // 构建 JSON 数据
            val json = """
                {
                    "username": "$username",
                    "password": "$password"
                }
            """.trimIndent()

            // 发送登录请求
            sendPostRequest(Constant.login_url, json);


        }
    }


    private fun sendPostRequest(url: String, json: String) {
        val requestBody =
            RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json)
        val request = Request.Builder()
            .url(url)
            .post(requestBody)
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                runOnUiThread {
                    Toast.makeText(this@SignActivity, "请求失败: ${e.message}", Toast.LENGTH_SHORT)
                        .show()
                }
            }

            override fun onResponse(call: Call, response: Response) {
                if (!response.isSuccessful) {
                    runOnUiThread {
                        Toast.makeText(
                            this@SignActivity,
                            "服务器返回: ${response.code()} + ${response.message()}",
                            Toast.LENGTH_LONG
                        ).show()
                    }
                    return
                }

                val responseBody = response.body()?.string()
                if (response.code() == 200) {
                    // 登录成功，跳转到 MainActivity
                    runOnUiThread {
                        Toast.makeText(this@SignActivity, "登录成功！", Toast.LENGTH_SHORT).show()
                        val intent = Intent(this@SignActivity, MainActivity::class.java)
                        startActivity(intent)
                        finish()  // 关闭当前登录界面
                    }
                } else {
                    // 登录失败，显示错误信息
                    runOnUiThread {
                        Toast.makeText(
                            this@SignActivity,
                            "登录失败: $responseBody",
                            Toast.LENGTH_LONG
                        ).show()
                    }
                }
            }
        })
    }
}